package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var Config *MongoCfg
var MongoClient *mongo.Client

type MongoCfg struct {
	Username      string
	Password      string
	AuthMechanism string
	AuthSource    string

	Timeout        int
	HostsWithPorts []string
	MaxPool        uint64
	MinPool        uint64
	ReplicaSet     string
}

func Connect() {
	conf := &MongoCfg{
		Username: "root",
		// Username: "stu",
		// Password: "123456",
		Password:      "iam59!z$",
		AuthMechanism: "SCRAM-SHA-1",
		AuthSource:    "mytest",

		Timeout:        10,
		HostsWithPorts: []string{"192.168.128.210:27017"},
		MaxPool:        20,
		MinPool:        10,
		ReplicaSet:     "",
	}

	credential := options.Credential{
		Username: conf.Username,
		Password: conf.Password,
		// AuthMechanism: conf.AuthMechanism,
		// AuthSource:    conf.AuthSource,
	}

	clientOps := options.Client().SetAuth(credential).
		// SetConnectTimeout(time.Duration(conf.Timeout * 1000)).
		SetHosts(conf.HostsWithPorts).
		SetMaxPoolSize(conf.MaxPool).
		SetMinPoolSize(conf.MinPool)
	// SetReadPreference()

	var ctx = context.TODO()
	client, err := mongo.Connect(ctx, clientOps)
	if nil != err {
		panic(err)
	}

	err = client.Ping(ctx, nil)
	if nil != err {
		fmt.Println(err)
		return
	}
	MongoClient = client
}
